# 1606 困难：找到处理最多请求的服务器

from sortedcontainers import SortedList


class Solution:
    # def busiestServers(self, k: int, arrival: List[int], load: List[int]) -> List[int]:
    def busiestServers(self, k, arrival, load):
        cnt = [1 for i in range(k)]
        time = [0] * k
        begin = 0
        for i in range(len(arrival)):
            for j in range(k):
                if time[j] > arrival[i] - begin:
                    time[j] -= arrival[i] - begin
                else:
                    time[j] = 0
            begin = arrival[i]
            print(time)

            ser = i % k
            flag = 0

            # 判断使用那个服务器
            while time[ser] != 0:
                if flag == k:
                    break
                ser = (ser + 1) % k
                flag += 1
            # 服务器全不空，舍弃请求
            if flag == k:
                print('continue')
                continue
            else:
                cnt[ser] += 1
                time[ser] += load[i]
            print(time)

        ret = []
        # print(cnt)
        maxm = max(cnt)
        for i in range(k):
            if cnt[i] == maxm:
                ret.append(i)
        return ret

    from sortedcontainers import SortedList

    # class Solution:
    #     def busiestServers(self, k: int, arrival: List[int], load: List[int]) -> List[int]:
    #         available = SortedList(range(k))
    #         busy = []
    #         requests = [0] * k
    #         for i, (start, t) in enumerate(zip(arrival, load)):
    #             while busy and busy[0][0] <= start:
    #                 available.add(busy[0][1])
    #                 heappop(busy)
    #             if len(available) == 0:
    #                 continue
    #             j = available.bisect_left(i % k)
    #             if j == len(available):
    #                 j = 0
    #             id = available[j]
    #             requests[id] += 1
    #             heappush(busy, (start + t, id))
    #             available.remove(id)
    #         maxRequest = max(requests)
    #         return [i for i, req in enumerate(requests) if req == maxRequest]



s = Solution()
print(s.busiestServers(3, [1,2,3,4,5], [5,2,3,3,3]))
print(s.busiestServers(2, [1,4,5,7], [3,2,7,8]))



